package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.GoodsCategory;
import com.example.mapper.GoodsCategoryMapper;
import com.example.service.GoodsCategoryService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class GoodsCategoryServiceImpl implements GoodsCategoryService {
    @Resource
    private GoodsCategoryMapper goodsCategoryMapper;

    @Override
    public List<GoodsCategory> getGoodsCategoryList() {
        QueryWrapper<GoodsCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("parent_id");
        List<GoodsCategory> categories = goodsCategoryMapper.selectList(queryWrapper);
        Map<Integer, GoodsCategory> categoryMap = new HashMap<>();
        for (GoodsCategory category : categories) {
            categoryMap.put(category.getId(), category);
        }
        // 创建一个list，用于保存一级分类
        List<GoodsCategory> topLevelCategories = new ArrayList<>();

        for (GoodsCategory category : categories) {
            if (category.getParentId() == null || category.getParentId() == 0) {
                topLevelCategories.add(category);
            } else {
                GoodsCategory parentCategory = categoryMap.get(category.getParentId());
                if (parentCategory != null) {
                    if (parentCategory.getChildren() == null) {
                        parentCategory.setChildren(new ArrayList<>());
                    }
                    // 将当前分类添加到父分类的子列表中
                    parentCategory.getChildren().add(category);
                }
            }
        }
        return topLevelCategories;
    }

    @Override
    public Long getGoodsCategoryIdByName(String name) {
        return goodsCategoryMapper.getGoodsCategoryIdByName(name);
    }

    @Override
    public List<Long> getChildrenByPatent(Long parentId) {
        return goodsCategoryMapper.getChildrenByPatent(parentId);
    }

    @Override
    public int addChildrenCategory(GoodsCategory child) {
        return goodsCategoryMapper.insert(child);
    }

    @Override
    public int updateStatus(boolean status,Long categoryId) {
        return goodsCategoryMapper.updateStatus(status,categoryId);
    }

    @Override
    public int editCategory(GoodsCategory goodsCategory) {
        LambdaQueryWrapper<GoodsCategory> updateWrapper = new LambdaQueryWrapper<>();
        updateWrapper.eq(GoodsCategory::getId,goodsCategory.getId());

        int rows = goodsCategoryMapper.update(goodsCategory,updateWrapper);
        return rows;
    }
}